package com.xinqi.modules.prepare.common.manager.impl;

import com.xinqi.common.redis.utils.Caches;
import com.xinqi.modules.prepare.common.dto.UserBaseInfoDO;
import com.xinqi.modules.prepare.common.manager.PrepareCommonManager;
import com.xinqi.modules.prepare.common.mapper.PrepareCommonMapper;
import com.xinqi.modules.prepare.prepare.domain.PrepareEntity;
import com.xinqi.modules.prepare.prepare.dto.req.PrepareUserQueryDTO;
import com.xinqi.modules.prepare.prepare.mapper.PrepareMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static com.xinqi.modules.prepare.common.constant.PrepareCacheConstant.PREPARE_BASE_INFO_KEY;
import static com.xinqi.modules.prepare.common.constant.PrepareCacheConstant.USER_BASE_INFO_KEY;

/**
 * 备课区公共 实现层
 *
 * @author linkai
 * @date 2023/3/21
 */
@Service
@RequiredArgsConstructor
public class PrepareCommonManagerImpl implements PrepareCommonManager {
    private final PrepareCommonMapper prepareCommonMapper;
    private final PrepareMapper prepareMapper;
    private final RedissonClient redissonClient;

    @Override
    public UserBaseInfoDO findUserById(Long userId) {
        // 添加缓存
        return Caches.get(() -> {
            List<UserBaseInfoDO> user = prepareCommonMapper.findUser(userId, null, null, null);
            return CollectionUtils.isNotEmpty(user) ? user.get(0) : null;
        }, redissonClient, USER_BASE_INFO_KEY, userId);
    }

    @Override
    public PrepareEntity findPrepareById(Long prepareId) {
        // 添加缓存
        return Caches.get(
            () -> prepareMapper.selectById(prepareId),
            redissonClient, PREPARE_BASE_INFO_KEY, prepareId
        );
    }

    @Override
    public boolean existsUser(Long userId) {
        return Optional.ofNullable(findUserById(userId)).isPresent();
    }

    @Override
    public List<UserBaseInfoDO> findUserList(PrepareUserQueryDTO dto) {
        return prepareCommonMapper.findUserList(dto);
    }

}
